<%@page import="java.sql.*"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<jsp:useBean id="ubbt" class="store.book.javabean.User_Buy_Books_Table"></jsp:useBean>
<%
	String user_email = (String) session.getAttribute("user_email");
	if (user_email == null) {//如果用户没有登录就直接访问则跳转到index.jsp
		response.sendRedirect("index.jsp");
	} else {
		ubbt.setUser_email(user_email);

		//将用户选中的商品添加到购物车
		String bookid = request.getParameter("bookid");
		String booknum = request.getParameter("booknum");
		boolean isExistForCart = false;//标记购物车中是否存在某商品

		if (bookid != null && booknum != null) {//执行将商品添加到购物车的功能
			try {
			ResultSet rs = ubbt.getUserBuyBooks(ubbt);
			if (rs.next()) {
				do {
					if (bookid.equals(rs.getLong("book_id"))
							&& booknum.equals(rs
									.getString("user_email"))) {
						isExistForCart = true;//存在
						break;
					}
				} while (rs.next());
			}
			
			if (!isExistForCart) {//当购物车不存在所选商品执行添加
				ubbt.setBook_id(Long.parseLong(bookid));
				ubbt.setBuy_num(Integer.parseInt(booknum));
				ubbt.setUser_email(user_email);
				ubbt.addBookToCart(ubbt);//添加到购物车
			}
			} catch (Exception e) {}
		}
		
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我的购物车 - BookStore</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-theme.min.css" rel="stylesheet">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->
<!-- 注意： 如果通过 file://  引入 Respond.js 文件，则该文件无法起效果 -->
<!--[if lt IE 9]>
         	<script src="js/html5shiv.min.js"></script>
        	<script src="js/respond.min.js"></script>
     	<![endif]-->

<style>
.select { /*display: none;*/
	
}

.select span {
	padding: 1px;
}

button {
	outline: none;
}
</style>
</head>
<body>
	<!-- 若用户没有选择任何一项就点击结算按钮，则提示进行选择 -->
	<%
		String noSelect = request.getParameter("noSelect");
		if (noSelect != null) {
			if ("true".equals(noSelect)) {
	%>
	<div class="alert alert-danger alert-dismissable" id="alert">
		<button type="button" class="close" id="close" data-dismiss="alert"
			aria-hidden="true">&times;</button>
		<p id="error">请选择任意一项进行结算！</p>
	</div>
	<script type="text/javascript">
		var close = document.getElementById('close');
		close.onclick = function() {
			location.href = "cart.jsp";
		};
	</script>
	<%
			}
		}
	%>

	<div class="panel panel-info">
		<div class="panel-heading">
			<span class="glyphicon glyphicon-shopping-cart"></span>
			全部书籍&nbsp;<span class="badge" id="booksItem"></span>
		</div>
		<div class="panel-body table-responsive">
			<table class="table table-striped">
				<thead>
					<tr class="text-muted">
						<th>书名</th>
						<th>作者</th>
						<th>单价</th>
						<th>数量</th>
						<th>小计</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
					<%
						try {
						ResultSet rs = ubbt.getUserBuyBooks(ubbt);
							if (rs.next()) {
					%>
					<script>
						var booksItem = 0;
					</script>
					<%
						do {
					%>
					<tr>
						<td class="col-xs-3"><br />
						<strong><%=rs.getString("book_name")%></strong>
						</td>
						<td class="text-info col-xs-2"><br /><%=rs.getString("book_author")%></td>
						<td class="text-danger col-xs-2"><br />¥<span><fmt:formatNumber
								value='<%=rs.getDouble("book_price")%>' pattern="0.00"></fmt:formatNumber></span>
						</td>
						<td class="col-xs-2"><br>
							<form action="servlet/ModifyCartBooksNum" method="post">
							<div class="input-group input-group-sm col-xs-5">
							<span class="input-group-btn">
							<button type="submit" value="minusone" name="minusone" class="btn btn-default">-</button>
							</span>
							<input type="text" class="form-control" name="buynum" readonly="readonly" value='<%=rs.getInt("buy_num")%>' />
							<input type="text" name="bookid" value='<%=rs.getLong("book_id")%>' style="display: none;" /><!-- 不显示此输入框，只用于向后台传递book_id -->
							<span class="input-group-btn">
							<button type="submit" value="addone" name="addone" class="btn btn-default">+</button>
							</span>
							</div>
							</form>
						</td>						
						<td class="text-danger col-xs-1"><br />¥<span id="totalTool"><fmt:formatNumber
								value='<%=rs.getDouble("book_price") * rs.getInt("buy_num")%>'
								pattern="0.00"></fmt:formatNumber></span>
						</td>
						<td class="select col-xs-1" style="text-align: center;">
						<div style="margin-right: 63px;">
						<form action="servlet/RemoveBooksFromCart" method="post">
							<button type="submit" value='<%=rs.getLong("book_id")%>' name="deleteItem" style="background: none; border: none;">
								&times;
							</button>
						</form>
						<input
							type="checkbox" class="singleSelect" name="singleSelect"
							value="<%=rs.getDouble("book_price")%>/<%=rs.getInt("buy_num")%>/<%=rs.getLong("book_id")%>"
							onclick="singleSelect(this)" />
							</div>
						</td>
					</tr>
					<script>
						booksItem++;
					</script>
					<%
						} while (rs.next());
						
					%>
					<script>
						document.getElementById('booksItem').innerHTML = "&nbsp;"
								+ booksItem + "&nbsp;";
					</script>
					<%
						} else {}
						
					} catch (SQLException e) {}
					%>
				</tbody>
			</table>
		</div>
		<div class="panel-footer">
			<input id="all" type="checkbox" /> <label for="all"
				class="text-muted">全选</label>
			<button type="button" onclick="cartSettleAccounts()" class="btn btn-success pull-right">结算</button>
			<div class="pull-right" style="padding-right: 10px;">
				已选择：<strong id="alreadySelect" class="text-danger">0</strong>&nbsp;本<br /> 总价：<strong id="total" class="text-danger">0.00</strong>&nbsp;元
			</div>
		</div>
	</div>

	<script>
		//选中购物车中的商品进行结算
		function singleSelect(self) {

			var singleSelect = document.getElementsByClassName('singleSelect');
			var flag = 1;
			for ( var i = 0; i < singleSelect.length; i++) {
				if (!singleSelect[i].checked) {//取消选中某项时取消全选复选框
					document.getElementById('all').checked = false;
				}
			}
			for ( var i = 0; i < singleSelect.length; i++) {
				if (!singleSelect[i].checked) {
					flag = 0;
					break;
				}
			}
			if (flag == 1) {//当通过单一复选框选中所有项就勾选全选复选框
				document.getElementById('all').checked = true;
			}

			var price = self.value.split("/")[0];
			var num = self.value.split("/")[1];
			if (self.checked) {
				document.getElementById('total').innerHTML = (eval(document
						.getElementById('total').textContent) + price * num)
						.toFixed(2);
				document.getElementById('alreadySelect').innerHTML = eval(document
						.getElementById('alreadySelect').textContent)
						+ eval(num);
			} else {
				document.getElementById('total').innerHTML = (eval(document
						.getElementById('total').textContent) - price * num)
						.toFixed(2);
				document.getElementById('alreadySelect').innerHTML = eval(document
						.getElementById('alreadySelect').textContent)
						- eval(num);
				if (document.getElementById('total').textContent < 0) {
					document.getElementById('total').innerHTML = (0).toFixed(2);
				}
				if (document.getElementById('alreadySelect').textContent < 0) {
					document.getElementById('alreadySelect').innerHTML = 0;
				}
			}
		}
		
		//在购物车中点击结算按钮，去trade.jsp进行结算
		function cartSettleAccounts() {//购物车结算
			var singleSelect = document.getElementsByClassName('singleSelect');
			var num = [];
			var id = [];
			
			var isChecked = 0;//是否选中的标记
			for (var i = 0; i < singleSelect.length; i++) {
				if (singleSelect[i].checked) {
					num.push(singleSelect[i].value.split("/")[1]);
					id.push(singleSelect[i].value.split("/")[2]);
				} else {
					isChecked++;
				}
			}
			
			if (isChecked == singleSelect.length) {//表示用户一个书籍都没有选,此时不让用户提交
				location.href = "cart.jsp?noSelect=true";
			} else {
				location.href = "trade.jsp?" + "bookid=" + id + "&booknum=" + num;
			}
		}
	</script>

	<!-- jQuery (Bootstrap 的 JavaScript 插件需要引入 jQuery) -->
	<script src="js/jquery-3.1.1.min.js"></script>
	<!-- 包括所有已编译的插件 -->
	<script src="js/bootstrap.min.js"></script>

	<script type="text/javascript">
		//点击全选选中所有商品
		$('#all').click(
						function() {
							var singleSelect = document
									.getElementsByClassName('singleSelect');

							var price = 0;
							var num = 0;
							if (document.getElementById('all').checked) {
								for ( var i = 0; i < singleSelect.length; i++) {
									singleSelect[i].checked = true;
									price = price
											+ singleSelect[i].value.split("/")[0]
											* singleSelect[i].value.split("/")[1];
									num = num
											+ eval(singleSelect[i].value
													.split("/")[1]);
								}

								document.getElementById('total').innerHTML = price
										.toFixed(2);
								document.getElementById('alreadySelect').innerHTML = num;
							} else {
								for ( var i = 0; i < singleSelect.length; i++) {
									singleSelect[i].checked = false;
								}

								document.getElementById('total').innerHTML = (0)
										.toFixed(2);
								document.getElementById('alreadySelect').innerHTML = 0;
							}
						});
	</script>
</body>

</html>
<%
	}
%>
